<?php
declare(strict_types=1);

/**
 * 高德地址ip解析
 */
namespace Service\VendorClient\Amap;
use Service\BaseService;
use Service\Code\Normal;
use Service\ExtraService\IdService;
use App\Service\TaskServer\TaskWorker;
class AmapApiClient extends BaseService
{
    protected $config;
    public function __construct(array $apiBody = [])
    {
        $this->config = $apiBody;
    }

    /**
     * 查询ip归属地址
     * @param $params
     * @return mixed
     */
    public function queryAddressByIp(string $ip)
    {
        if( empty($this->config['baseurl']) ) {
            return Normal::returnCode(Normal::FAIL,"当前高德查询ip归属地址baseurl未配置");
        }
        $url = $this->config['baseurl']."?ip={$ip}&output=json&key={$this->config['key']}";
        $parameter = [
            [
                'tag'       => 'amap_ip_query',
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => [],
                'method'    => 'GET',
                'format'    => 'x-www-form-urlencoded',
                'header'    => [],
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res, true);
        $errorMsg = $resHttp['info'] ?? '高德ip地址归属查询请求失败，请联系高德客服解决!';
        if (isset($resHttp['status']) && $resHttp['status'] == '1') {
            return Normal::returnCode(Normal::SUC, "操作成功",[
                'province'  => $resHttp['province'],
                'city'      => $resHttp['city'],
                'district'  => '',
                'ip'        => $ip
            ]);
        }
        return Normal::returnCode(Normal::FAIL, $errorMsg);
    }
}